﻿using Business;
using Model;
using Public;
using Public.Tools;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web;
using System.Web.Http;
using wochu.DPS.API.Infrastructure;

namespace wochu.DPS.API.Controllers
{
    public class UpdateVersionController : ApiController
    {
        private static UpdateVersionBll _NewInstance = new UpdateVersionBll();

        public static UpdateVersionBll NewInstance
        {
            get
            {
                if (_NewInstance == null)
                {
                    _NewInstance = new UpdateVersionBll();
                }

                return _NewInstance;
            }
        }

        [HttpGet]
        public HttpResponseMessage CheckAppVersion(int majorId, int buildNo)
        {
            SysSetting se = new SysSetting();
            string _resultDirecPath = NewInstance.CheckAppVersion(majorId, buildNo);
            if (!string.IsNullOrEmpty(_resultDirecPath))
            {
                return ResultsExtensions.GetSuccessJson(_resultDirecPath);
            }
            else
            {
                se.Key = Consts.strFalse;
                se.Value = "已经是最新版本，无需更新";
                return ResultsExtensions.GetFailJson(se);
            }
        }
        [HttpGet]
        [ActionName("download")]
        public HttpResponseMessage GetLastAppVersion(int majorId, int buildNo)
        {
            VersionInfo version = NewInstance.GetLastAppVersion(majorId, buildNo);
            if (version == null || version.DownFiles.Count <= 0)
            {
                SysSetting se = new SysSetting();
                se.Key = Consts.strFalse;
                se.Value = "已经是最新版本，无需更新";
                return ResultsExtensions.GetFailJson(se);
            }
            else
            {
                string UP_APPPATH = AppDomain.CurrentDomain.SetupInformation.ApplicationBase + @"DownAppFile\" + version.RELEASENOTE + @"\" + version.DownFiles[0].FILENAME;
                FileStream fileStream = new FileStream(UP_APPPATH, FileMode.Open, FileAccess.Read, FileShare.Read);
                HttpResponseMessage response = new HttpResponseMessage();
                response.Content = new StreamContent(fileStream);
                response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
                response.Content.Headers.ContentDisposition.FileName = version.DownFiles[0].FILENAME;
                response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");  // 这句话要告诉浏览器要下载文件  
                response.Content.Headers.ContentLength = new FileInfo(UP_APPPATH).Length;
                return response;
            }
        }
  
    }
}
